Skip to content

Conversation

hcientist
Copy link
Member

in testing output, as in test_kiosk I needed to read the program's output. I was doing that with capsys, but apparently prompts given to python's input() function won't be available in the stdout as captured in this way. We could instruct students to use print specifically to output their prompts, but that feels unnecessarily fragile.

@hcientist hcientist changed the title apparently the prompts given to input() go to stderr when python isn't running, maybe this fixture would be helpful generally apparently the prompts given to input() go to stderr when python isn't running in tty, maybe this fixture would be helpful generally Sep 25, 2025
@ChrisMayfield
Copy link
Member

Thank you for the contribution. I would prefer to take a simpler approach for redirecting standard input than to use a custom fixture. The following approach does not cause prompts to go to stderr, and the user input is in the same format as other jmu_pytest_utils functions:

class redirect_stdin:
    """Context manager that temporarily redirects standard input."""

    def __init__(self, user_input):
        self.user_input = user_input

    def __enter__(self):
        sys.stdin = StringIO(self.user_input)

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdin = sys.__stdin__

Note: PEP8 would prefer the spelling RedirectStdin, but I'm following the style of contextlib that defines context managers for redirect_stdout and redirect_stderr.

You would use redirect_stdin like this:

@weight(1)
def test_welcome(capsys):
    """Prompt is displayed."""
    test_books_2 = [b for b in TEST_BOOKS_2_TEMPLATE]
    with redirect_stdin("0\n"):
        main(test_books_2)
    out, _ = capsys.readouterr()
    assert "Welcome to the Little Free Library!" in out, "Welcome message not displayed"
    assert "Please enter the number for the action you wish to perform:" in out, "Action prompt not displayed"

What do you think of this alternative to observable_stdin?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants